package study.web.service.socket.server.MultiThread;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class WeatherRunnable implements Runnable {
	
	private Socket socket ;
	
	public WeatherRunnable(Socket socket) {
		this.socket = socket ;
	}
	
	DataInputStream dataInputStream = null ;
	DataOutputStream dataOutputStream = null ;

	@Override
	public void run() {
		//接收客户端的请求
		try {
			//准备接受数据的流
			dataInputStream = new DataInputStream(socket.getInputStream()) ;
			//准备发送数据的流
			dataOutputStream = new DataOutputStream(socket.getOutputStream()) ;
			//接受客户端请求的数据（城市名称）
			String cityName = dataInputStream.readUTF() ;
			System.out.println("from client ... " + cityName);
			//处理数据 ... 休眠1秒
			Thread.sleep(3000) ;
			String result = "多云" ;
			//给客户端响应数据
			dataOutputStream.writeUTF(result) ;
			System.out.println("to client ... " + result);
		} catch (Exception e) {
			e.printStackTrace() ;
		} finally {
			//释放资源
			if(dataInputStream != null) {
				try {
					dataInputStream.close() ;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(dataOutputStream != null) {
				try {
					dataOutputStream.close() ;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
